﻿using System;
using System.Security.Cryptography;
using System.Text;

namespace Encrypt
{
    public class AES
    {
        public static string SimpleKey = "12345678876543211234567887654abc";
        /// <summary>
        ///  AES 加密
        /// </summary>
        /// <param name="str">明文（待加密）</param>
        /// <param name="key">密文</param>
        /// <returns></returns>
        public static string AesEncrypt(string str, string key)
        {
            if (string.IsNullOrEmpty(str)) return null;
            Byte[] toEncryptArray = Encoding.UTF8.GetBytes(str);
            var resBs = AesEncrypt(toEncryptArray, key);
            return Convert.ToBase64String(resBs, 0, resBs.Length);
        }
        /// <summary>
        ///  AES 加密
        /// </summary>
        /// <param name="bs">明文（待加密）</param>
        /// <param name="key">密文</param>
        /// <returns></returns>
        public static byte[] AesEncrypt(byte[] bs, string key)
        {
            RijndaelManaged rm = new RijndaelManaged
            {
                Key = Encoding.UTF8.GetBytes(key),
                Mode = CipherMode.ECB,
                Padding = PaddingMode.PKCS7
            };
            byte[] resultArray = null;
            using (ICryptoTransform cTransform = rm.CreateEncryptor())
            {
                resultArray = cTransform.TransformFinalBlock(bs, 0, bs.Length);
            }
            return resultArray;
        }
        /// <summary>
        ///  AES 解密
        /// </summary>
        /// <param name="str">明文（待解密）</param>
        /// <param name="key">密文</param>
        /// <returns></returns>
        public static string AesDecrypt(string str, string key)
        {
            if (string.IsNullOrEmpty(str)) return null;
            Byte[] toEncryptArray = Convert.FromBase64String(str);
            return Encoding.UTF8.GetString(AesDecrypt(toEncryptArray,key));
        }
        /// <summary>
        ///  AES 解密
        /// </summary>
        /// <param name="str">明文（待解密）</param>
        /// <param name="key">密文</param>
        /// <returns></returns>
        public static byte[] AesDecrypt(byte[] bs, string key)
        {
            RijndaelManaged rm = new RijndaelManaged
            {
                Key = Encoding.UTF8.GetBytes(key),
                Mode = CipherMode.ECB,
                Padding = PaddingMode.PKCS7
            };
            byte[] resultArray = null;
            using (ICryptoTransform cTransform = rm.CreateDecryptor())
            {
                resultArray = cTransform.TransformFinalBlock(bs, 0, bs.Length);
            }
            return resultArray;
        }
    }
}

